import 'dart:async';
import 'dart:convert';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class MyWebSocketChannel {
  WebSocketChannel? _channel;
  bool _isConnected = false;
  Timer? _heartbeatTimer;

  //重用 重连
  late String _savedUrl;
  late Function() _savedOnConnectSuccess;
  late Function(dynamic) _savedOnDataReceived;
  late Function(dynamic) _savedOnConnectFailure;
  late Map? _savedParam;

  MyWebSocketChannel();

  //链接
  Future<void> connect({
    required String url,
    required Function() onConnectSuccess,
    required Function(dynamic) onDataReceived,
    required Function(dynamic) onConnectFailure,
    Map? param,
  }) async {
    try {
      _channel = IOWebSocketChannel.connect(url);
      if (param != null) {
        _channel?.sink.add(jsonEncode(param));
      }
      _isConnected = true;
      _channel!.stream.listen((dynamic message) {
        onDataReceived(message);
      }).onDone(() {
        //关闭的时候
        _isConnected = false;
      });

      // 保存连接所需的参数
      _savedUrl = url;
      _savedOnConnectSuccess = onConnectSuccess;
      _savedOnDataReceived = onDataReceived;
      _savedOnConnectFailure = onConnectFailure;
      _savedParam = param;

      onConnectSuccess();
    } catch (e) {
      //链接失败的时候
      _isConnected = false;
      onConnectFailure(e);
    }
  }

  //断线重连
  void _cancelHeartbeatAndReconnect() {
    _heartbeatTimer?.cancel();
    _heartbeatTimer = null;
    _channel?.sink.close();

    // 使用保存的参数进行重新连接
    connect(
      url: _savedUrl,
      onConnectSuccess: _savedOnConnectSuccess,
      onDataReceived: _savedOnDataReceived,
      onConnectFailure: _savedOnConnectFailure,
      param: _savedParam,
    );
  }

  //判断链接状态
  // Future<bool> isWebSocketConnected() async {
  //   if (_channel == null) {
  //     return false;
  //   }
  //   await _channel!.sink.done;
  //   return _isConnected;
  // }

  bool isWebSocketConnected() {
    if (_channel == null) {
      return false;
    }
    return _isConnected;
  }

  //心跳
  void _startHeartbeat(
    dynamic data, {
    Function()? onSendMessageSuccess,
    Function(dynamic)? onSendMessageFailure,
    bool bIsHeartbeat = false, //是否需要心态
    int iHeartbeat = 60, //心态间隔
  }) {
    _heartbeatTimer = Timer.periodic(Duration(seconds: iHeartbeat), (timer) {
      sendMessage(data,
          onSendMessageSuccess: onSendMessageSuccess,
          onSendMessageFailure: onSendMessageFailure,
          bIsHeartbeat: bIsHeartbeat,
          iHeartbeat: iHeartbeat);
    });
  }

  //发送消息
  void sendMessage(
    dynamic data, {
    Function()? onSendMessageSuccess,
    Function(dynamic)? onSendMessageFailure,
    bool bIsHeartbeat = false, //是否需要心态
    int iHeartbeat = 60, //心态间隔
  }) {
    if (bIsHeartbeat) {
      _startHeartbeat(data, iHeartbeat: iHeartbeat);
    }

    try {
      if (!_isConnected) {
        print('WebSocket is not connected.');
        if (onSendMessageFailure != null) {
          onSendMessageFailure('WebSocket is not connected.');
        }

        print("PTWebSocketChannel------断线重连");
        _cancelHeartbeatAndReconnect();
      } else {
        _channel!.sink.add(data);
        print('Message sent successfully!');
        if (onSendMessageSuccess != null) {
          onSendMessageSuccess();
        }
      }
    } catch (e) {
      print('Message sending failed: $e');

      if (onSendMessageFailure != null) {
        onSendMessageFailure(e);
      }
    }
  }

  //关闭链接
  void close() {
    _heartbeatTimer?.cancel();
    _heartbeatTimer = null;
    _channel?.sink.close();
    _isConnected = false; // 设置连接状态为false
    _channel = null; // 释放_channel资源
    print('WebSocket connection closed.');
  }
}

//ws Url
class PTWSUrl {
  static const String emailWebSocketUrl =
      "wss://enterprise-mailservice.pintreel.com/wss"; // 邮件webSocket地址

  //谷歌搜索电话
  static String strPhoneNum =
      "ws://data-api.pintreel.com/api/google_search_contacts/phone_numbers/ws?";
  //谷歌搜索邮箱
  static String strEmails =
      "ws://data-api.pintreel.com/api/google_search_contacts/emails/ws?";
  //komPass数据
  static String strKomPass =
      "ws://data-api.pintreel.com/api/kompass/companies/search/ws?";

  //gpt搜索关键词
  static String strSoftwareAsk = "wss://ai.pintreel.com/api/v1/software/ask?";

  //gpt获取电话邮箱
  static String strPhoneEmail = "wss://wss.pintreel.com:2100";

  ///fb主页数据ws
  static const String fbDataUrl =
      "ws://data-api.pintreel.com/api/facebook_home_data/ws";

  ///gpt生成websocket
  static const String gptWebSocketUrl =
      "wss://ai.pintreel.com/api/v1/software/generate_email"; // gpt生成websocket

  static const String automationPushUrl =
      "ws://automate.pintreel.com/api/v1/task/automate_task_status_push"; //自动化推送

  //软件数据推送 wss://wss.pintreel.com:2100
  static const String softwarePushUrl = "wss://wss.pintreel.com:2100";
}
